<template>
  <div class="article-management">
    <!-- 标题与操作栏容器：用Flex实现对齐 -->
    <div class="header-container">
      <h2 class="page-title">文章内容</h2>
      <!-- 操作栏：移除固定margin-left，由Flex布局自动推到右侧 -->
      <div class="operation-bar">
        <el-select v-model="selectedCategory" placeholder="全部" style="width: 320px;">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="item in articleCategories" :key="item.categoryId" :label="item.categoryName" :value="item.categoryId">
          </el-option>
        </el-select>
        <el-button type="primary" style="margin-left: 10px;" @click="getArticleAll">筛选</el-button>
        <el-button type="primary" @click="addArticle">添加文章</el-button>
      </div>
    </div>

    <el-table :data="tableData" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="articleId" label="ID"></el-table-column>
      <el-table-column prop="articleCategories.categoryName" label="分类"></el-table-column>
      <el-table-column prop="coverImage" label="封面图">
        <template #default="scope">
          <el-image v-if="scope.row.coverImage" :src="scope.row.coverImage" style="width: 80px; height: 60px;"></el-image>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column prop="articleTitle" label="文章标题"></el-table-column>
      
      <el-table-column prop="createTime" label="日期">
        <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
       </template>
      </el-table-column>

      <el-table-column prop="publishStatus" label="审核">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.publishStatus">已审核</el-tag>
          <el-tag type="warning" v-else>未审核</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="articleCategories.sort" label="排序"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row.articleId)">编辑</el-button>
          <el-button type="danger" size="small" style="margin-left: 5px;" @click="handleDelete(scope.row.articleId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px;"
    >
    </el-pagination>
    
    <!-- 文章编辑模态框 -->
    <el-dialog
      title="文章编辑"
      v-model="dialogVisible"
      width="80%"
    >
      <el-form :model="Updateform" label-width="120px">
        <el-form-item label="分类" prop="articleCategories.categoryId">
          <el-select v-model="Updateform.articleCategories.categoryId" placeholder="请选择分类" style="margin-left: 10px;">
            <el-option label="请选择" value=""></el-option>
            <el-option 
              v-for="item in articleCategories" 
              :key="item.categoryId"  
              :label="item.categoryName" 
              :value="item.categoryId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="标题" prop="articleTitle">
          <el-input v-model="Updateform.articleTitle"></el-input>
        </el-form-item>
      
        <el-form-item label="封面图" prop="coverImage" class="avatar-item">
          <el-upload
            class="avatar-uploader"
            name="file"
            action="http://localhost:9520/serviceoss/fileoss/uploadAvatarToOss"
            :show-file-list="false"
            :on-success="(res) => handleEditAvatarSuccess(res)"
            :before-upload="beforeAvatarUpload"
          >
            <div class="avatar-wrapper">
              <img v-if="Updateform.coverImage" :src="Updateform.coverImage" class="avatar" style="height: 100px;width: 100px">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="排序" prop="articleCategories.sort">
          <el-input v-model.number="Updateform.articleCategories.sort"></el-input>
        </el-form-item>
        
        <el-form-item label="状态" prop="publishStatus">
          <el-radio-group v-model="Updateform.publishStatus">
            <el-radio :value="0">未审核</el-radio>
            <el-radio :value="1">已审核</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="saveForm">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 文章添加模态框 -->
    <el-dialog
      title="文章添加"
      v-model="addDialogVisible"
      width="80%"
    >
      <el-form :model="addForm" label-width="120px">
        <!-- 分类选择 -->
        <el-form-item label="分类" prop="articleCategories.categoryId">
          <el-select 
            v-model="addForm.articleCategories.categoryId" 
            placeholder="请选择分类" 
            style="margin-left: 10px;"
            required
          >
            <el-option label="请选择" value=""></el-option>
            <el-option 
              v-for="item in articleCategories" 
              :key="item.categoryId"  
              :label="item.categoryName" 
              :value="item.categoryId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 文章标题 -->
        <el-form-item label="标题" prop="articleTitle">
          <el-input 
            v-model="addForm.articleTitle" 
            placeholder="请输入文章标题" 
            required
          ></el-input>
        </el-form-item>
      
       <!-- 封面图上传 -->
        <el-form-item label="封面图" prop="coverImage" class="avatar-item">
          <el-upload
            class="avatar-uploader"
            name="file"
            action="http://localhost:9520/serviceoss/fileoss/uploadAvatarToOss"
            :show-file-list="false"
            :on-success="(res) => handleAddAvatarSuccess(res)"
            :before-upload="beforeAvatarUpload"
          >
            <div class="avatar-wrapper">
              <img 
                v-if="addForm.coverImage" 
                :src="addForm.coverImage" 
                class="avatar" 
                style="height: 100px; width: 100px; object-fit: cover;"
              >
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </el-upload>
        </el-form-item>

        <!-- 审核状态 -->
        <el-form-item label="状态" prop="publishStatus">
          <el-radio-group v-model="addForm.publishStatus">
            <el-radio :value="0">未审核</el-radio>
            <el-radio :value="1">已审核</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 保存按钮 -->
        <el-form-item>
          <el-button type="primary" @click="saveAddForm">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import httpInstance from '../../utils/http';
import { ElMessage,ElMessageBox  } from 'element-plus';

// 文章列表数据
const tableData = ref([]);
const articleCategories = ref([]);
const selectedCategory = ref('');
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const dialogVisible = ref(false);
const addDialogVisible = ref(false);

// 编辑表单数据
const Updateform = reactive({
  articleId: '',
  articleTitle: '',
  coverImage: '',
  publishStatus: 0,
  articleCategories: {
    categoryId: '',
    categoryName: '',
    sort: 0
  }
});

// 添加表单数据
const addForm = reactive({
  articleTitle: '',
  coverImage: '',
  publishStatus: 0,
  articleCategories: {
    categoryId: '',
    categoryName: '',
    sort: 0
  }
});

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  getArticleAll();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getArticleAll();
};

// 编辑操作
const handleEdit = (id) => {
  dialogVisible.value = true;
  getArticleById(id);
};

// 页面加载时获取数据
onMounted(() => {
  getArticleAll();
  getArticleCategories();
});

// 编辑表单上传图片成功处理
const handleEditAvatarSuccess = (res) => {
  Updateform.coverImage = res.data.url || res.data;
  ElMessage.success('图片上传成功');
};

// 添加表单上传图片成功处理
const handleAddAvatarSuccess = (res) => {
  addForm.coverImage = res.data.url || res.data;
  ElMessage.success('图片上传成功');
};

// 打开添加文章模态框
const addArticle = () => {
  // 重置表单
  addForm.articleTitle = '';
  addForm.coverImage = '';
  addForm.publishStatus = 0;
  addForm.articleCategories.categoryId = '';
  addForm.articleCategories.sort = 0;
  
  addDialogVisible.value = true;
};

// 图片上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式！');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB！');
    return false;
  }
  return true;
};

// 获取文章列表
const getArticleAll = async () => {
  try {
    const res = await httpInstance.post(
      `/eduservice/article/getArticlePage/${currentPage.value}/${pageSize.value}`,
      { categoryIdVo: selectedCategory.value }
    );
    tableData.value = res.data.list;
    total.value = res.data.total;
  } catch (error) {
    console.error("获取文章数据失败:", error);
    ElMessage.error("获取文章数据失败");
  }
};

// 获取文章分类
const getArticleCategories = async () => { 
  try {
    const res = await httpInstance.post(`/eduservice/articleCategory`);
    articleCategories.value = res.data;
  } catch (error) {
    console.error("获取分类失败:", error);
  }
};

// 获取文章详情
const getArticleById = async (id) => {
  try {
    const res = await httpInstance.get(`/eduservice/article/${id}`);
    const articleData = res.data;
    
    Updateform.articleId = articleData.articleId;
    Updateform.articleTitle = articleData.articleTitle;
    Updateform.coverImage = articleData.coverImage;
    Updateform.publishStatus = articleData.publishStatus;
    
    if (articleData.articleCategories) {
      Updateform.articleCategories.categoryId = articleData.articleCategories.categoryId;
      Updateform.articleCategories.categoryName = articleData.articleCategories.categoryName;
      Updateform.articleCategories.sort = articleData.articleCategories.sort || 0;
    }
  } catch (error) {
    console.error('获取文章详情失败:', error);
    ElMessage.error('获取文章详情失败');
  }
};

// 保存编辑
const saveForm = async () => {
  try {
    if (!Updateform.articleTitle || !Updateform.articleCategories.categoryId) {
      ElMessage.warning('请填写标题和选择分类');
      return;
    }

    const response = await httpInstance.put(`/eduservice/article`, Updateform);
    ElMessage.success('文章更新成功!');
    dialogVisible.value = false;
    getArticleAll();
  } catch (error) {
    console.error('文章更新失败:', error);
    ElMessage.error('文章更新失败');
  }
};

// 删除操作：先提示确认，再调用删除接口
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这篇文章吗？删除后无法恢复！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const res = await httpInstance.delete(`/eduservice/article/${id}`);
    ElMessage.success('文章删除成功！');
    getArticleAll();

  } catch (error) {
    if (error.type !== 'cancel') {
      console.error('删除文章失败：', error);
      ElMessage.error('文章删除失败，请重试！');
    }
  }
};

// 保存添加
const saveAddForm = async () => {
  try {
    if (!addForm.articleTitle || !addForm.articleCategories.categoryId) {
      ElMessage.warning('请填写标题和选择分类');
      return;
    }

    const response = await httpInstance.post(`/eduservice/article`, addForm);
    ElMessage.success('文章添加成功!');
    addDialogVisible.value = false;
    getArticleAll();
  } catch (error) {
    console.error('文章添加失败:', error);
    ElMessage.error('文章添加失败');
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr || typeof dateStr !== 'string') return '';
  return dateStr.replace('T', ' ');
};
</script>

<style scoped>
.article-management {
  padding: 20px;
}

/* 核心：标题与操作栏的容器，用Flex实现对齐 */
.header-container {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: space-between; /* 标题居左，操作栏居右 */
  margin-bottom: 20px; /* 与下方表格保持间距 */
}

/* 标题样式：加粗+调整大小，增强视觉 */
.page-title {
  font-weight: 700; /* 加粗 */
  font-size: 18px; /* 标题字体大小，与操作栏元素协调 */
  color: #333; /* 标题颜色，避免过浅 */
  margin: 0; /* 清除默认margin，避免影响对齐 */
}

/* 操作栏：清除固定margin-left，由Flex布局控制位置 */
.operation-bar {
  display: flex;
  align-items: center; /* 操作栏内部元素垂直居中 */
  gap: 10px; /* 元素之间统一间距，替代零散margin-left */
}

/* 修复：补充上传组件外层样式，确保不被其他元素遮挡 */
.avatar-item {
  display: flex;
  align-items: center;
  padding: 0 !important; 
}

/* 修复：明确上传容器的尺寸和可点击范围 */
.avatar-uploader {
  position: relative;
  width: 100px;
  height: 100px;
  margin-left: 10px; /* 与标签对齐 */
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff; /*  hover时提示可点击 */
}

/* 修复：图标居中显示，确保视觉上有点击引导 */
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}

/* 修复：图片填充容器，避免变形 */
.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持图片比例，避免拉伸 */
  display: block;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
}

.avatar-wrapper {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fafafa;
}
</style>
